package com.rongke.web.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.rongke.annotation.SourceAuthority;
import com.rongke.commons.JsonResp;
import com.rongke.commons.PageDto;
import com.rongke.enums.FileType;
import com.rongke.enums.SourceType;
import com.rongke.model.*;
import com.rongke.service.*;
import com.rongke.sms.SmsService;
import com.rongke.sms.SmsTempletEnum;
import com.rongke.utils.DateUtils;
import com.rongke.utils.OrderUtils;
import com.rongke.web.apix.TongDunSDKAuth;
import com.rongke.web.config.Config;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.springframework.web.bind.annotation.RequestMethod.GET;


/**
 * @version : Ver 1.0
 * @LoanOrderController
 * @Controller
 */
@RestController
@RequestMapping(value = "/api/loanOrder")
@Transactional
@CrossOrigin
public class LoanOrderController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private LoanOrderService loanOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserBankService userBankService;
    @Autowired
    private ParamSettingService paramSettingService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private AgreementService agreementService;
    @Autowired
    public Config config;
    @Autowired
    public AdminService adminService;
    @Autowired
    public MsgModelService msgModelService;
    @Autowired
    public SmsService smsService;
    @Autowired
    public PersonRecordService personRecordService;


    /**
     * @param loanOrder
     * @return 返回值JsonResp
     * @添加
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addLoanOrder(@RequestBody LoanOrder loanOrder) {
        log.debug("添加");
        loanOrderService.insert(loanOrder);
        return JsonResp.ok(loanOrder);
    }

    /**
     * @param loanOrder
     * @return 返回值JsonResp
     * @修改
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateLoanOrder(@RequestBody LoanOrder loanOrder) {
        log.debug("修改");
        loanOrderService.updateById(loanOrder);
        return JsonResp.ok(loanOrder);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找
     */
    @RequestMapping(value = "/selectOne", method = GET)
    public JsonResp selectLoanOrder(Long id) {
        log.debug("查找");
        LoanOrder loanOrder = loanOrderService.selectById(id);
        return JsonResp.ok(loanOrder);
    }

    @RequestMapping(value = "/selectApplyStatus", method = GET)
    public JsonResp selectApplyStatus(HttpServletRequest request) {
        Map map = new HashMap();
        User user = userService.findLoginUser();
        List<LoanOrder> l = loanOrderService.selectApplyStatus(user.getId());
        if (l.size() != 0) {
            Integer s = l.get(0).getOrderStatus();
            map.put("status", s);
            if (user.getStatus() == 4) {
                Date startdate = l.get(0).getGmtDatetime();
                Calendar cal = Calendar.getInstance();
                cal.setTime(startdate);
                cal.add(Calendar.DATE, 1);
                map.put("refuseTime", (new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(cal.getTime()));
            }
        }
        return JsonResp.ok(map);
    }

    @RequestMapping(value = "/selectApplyNum", method = GET)
    public JsonResp selectApplyNum() {
        Map map = new HashMap();
        User user = userService.findLoginUser();
        EntityWrapper ew = new EntityWrapper();
        ew.eq("user_id", user.getId());
        ew.eq("pay_status", "1");
        List<LoanOrder> l = loanOrderService.selectList(ew);
        Integer nums = Integer.valueOf(systemConfigService.selectValueByKey("dabiaocishu"));
        if (l.size() <= nums) {
            map.put("success", "0");
            return JsonResp.ok(map);
        } else {
            map.put("success", "1");
            return JsonResp.ok(map);
        }
    }

    /**
     * @param
     * @return 返回值JsonResp
     * @生成未申请订单
     */
    @RequestMapping(value = "/addNewOrder", method = GET)
    public JsonResp addNewOrder(BigDecimal borrowMoney, Integer limitDays, Long userId, HttpServletRequest request) throws IOException, DocumentException, ParseException {

//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//        String date = df.format(new Date());
//        String everydayResetTime = systemConfigService.selectValueByKey("everydayResetTime");
//        date += " "+everydayResetTime+":00:00";
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date2 = sdf.parse(date);
//        Long rTime = date2.getTime();
//        Long nTime = new Date().getTime();
//        String endTime = "";
//        if(rTime>nTime){
//            endTime = sdf.format(nTime - 86400000);
//        }else{
//            endTime = sdf.format(nTime + 86400000);
//        }
//        List<LoanOrder> l = loanOrderService.selectApplyByTime(date,endTime);
//        if(l.size()>200){
//            return JsonResp.fa("今日申请已达到上限");
//        }

        log.debug("生成订单");
//        User user = userService.findLoginUser();
        User user = userService.selectById(userId);
        if (user.getIsPay() == 1) {
            return JsonResp.fa("你有订单正在审核或还款！");
        } else if (user.getStatus() == 2) {
            return JsonResp.fa("你的信用已不足！");
        } else if (user.getMoney().compareTo(borrowMoney) == -1) {
            return JsonResp.fa("你的额度不足！");
        } else {
            LoanOrder loanOrder = new LoanOrder();
            loanOrder.setUserId(user.getId());
            //银行信息
/*            EntityWrapper<UserBank> ew = new EntityWrapper<>();
            ew.eq("user_id", user.getId());
            UserBank userBank = userBankService.selectOne(ew);
            loanOrder.setBankCardNum(userBank.getBankcardno());
            loanOrder.setBankName(userBank.getBankName());*/
            EntityWrapper<UserIdentity> ew = new EntityWrapper<>();
            ew.eq("user_id", user.getId());
            UserIdentity userIdentity = userIdentityService.selectOne(ew);
            //计算费用
            EntityWrapper<ParamSetting> ew2 = new EntityWrapper<>();
            ew2.eq("limit_days", limitDays);
            ew2.eq("status", 1);
            ParamSetting paramSetting = paramSettingService.selectOne(ew2);
            loanOrder.setParamSettingId(paramSetting.getId());
            loanOrder.setInterestPrecent(paramSetting.getInterestPercent());
            loanOrder.setAllowDays(paramSetting.getAllowDays());
            BigDecimal interestMoney = borrowMoney.multiply(BigDecimal.valueOf(paramSetting.getInterestPercent() / 1000));
            BigDecimal placeServeMoney = borrowMoney.multiply(BigDecimal.valueOf(paramSetting.getPlaceServePercent() / 100));
            BigDecimal msgAuthMoney = borrowMoney.multiply(BigDecimal.valueOf(paramSetting.getMsgAuthPercent() / 100));
            BigDecimal riskServeMoney = borrowMoney.multiply(BigDecimal.valueOf(paramSetting.getRiskServePercent() / 100));
            BigDecimal riskPlanMoney = borrowMoney.multiply(BigDecimal.valueOf(paramSetting.getRiskPlanPercent() / 100));
            BigDecimal allWasteMoney = interestMoney.add(placeServeMoney).add(msgAuthMoney).add(riskServeMoney).add(riskPlanMoney);
            BigDecimal realMoney = borrowMoney.subtract(allWasteMoney);
            loanOrder.setBorrowMoney(borrowMoney);
            loanOrder.setLimitDays(limitDays);
            loanOrder.setRealMoney(realMoney);
            loanOrder.setWateMoney(allWasteMoney);
            loanOrder.setInterestMoney(interestMoney);
            loanOrder.setPlaceServeMoney(placeServeMoney);
            loanOrder.setMsgAuthMoney(msgAuthMoney);
            loanOrder.setRiskPlanMoney(riskPlanMoney);
            loanOrder.setRiskServeMoney(riskServeMoney);
            loanOrder.setNeedPayMoney(borrowMoney);
            loanOrder.setOrderStatus(0);
            //还款时间
            Date limitPayTime = DateUtils.dayAdd(paramSetting.getLimitDays(), new Date());
            loanOrder.setLimitPayTime(limitPayTime);
            //超出容限期时间
            Date overdueTime = DateUtils.dayAdd(paramSetting.getAllowDays(), limitPayTime);
            loanOrder.setOverdueTime(overdueTime);

            /* 生成借款和借款服务协议开始*/

            //获得合同模板
            EntityWrapper<Agreement> ewAgreement = new EntityWrapper<>();
            ew.eq("type", 1);
            String htmlstr = agreementService.selectOne(ewAgreement).getContent();
            //替换掉标签
            String orderNumber = OrderUtils.getOrderNo();
            String newHtml = htmlstr.replace("#money",
                    borrowMoney.toString()).replace("#number", orderNumber).replace("#jiafang",
                    user.getUserName()).replace("#identityNum", userIdentity.getIdentityNum())
//                    .replaceAll("#bankCardNum", userBank.getBankcardno())
                    .replace("#date",
                            DateUtils.dateSimple(new Date())).replace("#borrowDate",
                            DateUtils.dateSimple(new Date())).replace("#limitDays",
                            limitDays.toString()).replace("#interestMoney",
                            interestMoney.toString()).replace("#interestMoney",
                            interestMoney.toString()).replace("#userName",
                            user.getUserName()).replaceAll("宋体", "SimSun").replace("宋体", "SimSun");
            //在服务器端生成pdf的路径
            String[] paths = FileType.getPath(FileType.OTHER, 1, request);
            String path = paths[0] + File.separator + orderNumber + "1.pdf";
            //创建html转成pdf
            StringBuilder html = new StringBuilder();
            html.append("<html>");
            html.append("<body style='font-size:20px;font-family:SimSun;'>");
            html.append(newHtml);
            html.append("</body>");
            html.append("</html>");

            InputStream is = new ByteArrayInputStream(html.toString().getBytes());
            OutputStream os = new FileOutputStream(path);

            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, os);

            document.open();

            // 将html转pdf
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);

            document.close();
            File saveFile = new File(path);
            String savePath = config.getUploadHost(request, null, saveFile.getParentFile().getName(), saveFile.getName());
            loanOrder.setAgreementUrl(savePath);

            //借款服务协议
            EntityWrapper<Agreement> ewAgreement2 = new EntityWrapper<>();
            ewAgreement2.eq("type", 2);
            String htmlstr2 = agreementService.selectOne(ewAgreement2).getContent();
            //替换掉标签
//            String newHtml2 = htmlstr2.replace("#date", DateUtils.dateSimple(new Date())).replace("#number", orderNumber).replace("#userName", user.getUserName()).replace("#identityNum", userIdentity.getIdentityNum());
            String newHtml2 = htmlstr2.replace("#date", DateUtils.dateSimple(new Date()))
                    .replace("#number", orderNumber)
                    .replace("#userName", user.getUserName())
                    .replace("#identityNum", userIdentity.getIdentityNum())
                    .replace("#serveMoney", loanOrder.getWateMoney().subtract(loanOrder.getInterestMoney()).toString())
                    .replace("#msgAuthMoney", loanOrder.getMsgAuthMoney().toString())
                    .replace("#riskServeMoney", loanOrder.getRiskServeMoney().toString())
                    .replace("#riskPlanMoney", loanOrder.getRiskPlanMoney().toString())
                    .replace("#placeServeMoney", loanOrder.getPlaceServeMoney().toString());
            ;
            //在服务器端生成pdf的路径
            String[] paths2 = FileType.getPath(FileType.OTHER, 1, request);
            String path2 = paths2[0] + File.separator + orderNumber + "2.pdf";
            //创建html转成pdf
            StringBuilder html2 = new StringBuilder();
            html2.append("<html>");
            html2.append("<body style='font-size:20px;font-family:SimSun;'>");
            html2.append(newHtml2);
            html2.append("</body>");
            html2.append("</html>");

            InputStream is2 = new ByteArrayInputStream(html2.toString().getBytes());
            OutputStream os2 = new FileOutputStream(path2);

            Document document2 = new Document();
            PdfWriter writer2 = PdfWriter.getInstance(document2, os2);

            document2.open();

            // 将html转pdf
            XMLWorkerHelper.getInstance().parseXHtml(writer2, document2, is2);

            document2.close();
            File saveFile2 = new File(path2);
            String savePath2 = config.getUploadHost(request, null, saveFile2.getParentFile().getName(), saveFile2.getName());
            loanOrder.setAgreementTwoUrl(savePath2);
            /*生成借款和借款服务协议结束*/


            loanOrderService.insert(loanOrder);


            return JsonResp.ok(loanOrder);
        }

    }

    /**
     * @param
     * @return 返回值JsonResp
     * @使用优惠卷
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/useCoupon", method = GET)
    public JsonResp selectLoanOrder(Long userCouponId, Long orderId) {
        log.debug("使用优惠卷");
        UserCoupon userCoupon = userCouponService.selectById(userCouponId);//提交申请后再改状态
        LoanOrder loanOrder = loanOrderService.selectById(orderId);
        loanOrder.setUserCouponId(userCouponId);
        loanOrder.setSaveMoney(userCoupon.getSaveMoney());
        //应付金额减减免
        loanOrder.setNeedPayMoney(loanOrder.getBorrowMoney().subtract(userCoupon.getSaveMoney()));
        loanOrderService.updateById(loanOrder);
        return JsonResp.ok(loanOrder);
    }

    @Autowired
    private UserBasicMsgService userBasicMsgService;
    @Autowired
    private MobileService mobileService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private UserIdentityService userIdentityService;
    @Autowired
    private TongdunAuditService tongdunAuditService;

    /**
     * @param
     * @return 返回值JsonResp
     * @确认提交申请
     */
    //@SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/confirmOrder", method = GET)
    public JsonResp confirmOrder(Long orderId, Long userId) throws ParseException {


        log.debug("确认提交申请");
        LoanOrder loanOrder = loanOrderService.selectById(orderId);
        //生成订单号
        String orderNumber = OrderUtils.getOrderNo();
        loanOrder.setOrderNumber(orderNumber);
        //扣额度，改变is_pay
//        User user = userService.findLoginUser();
        User user = userService.selectById(userId);
        if (user.getStatus() == 1) {
            user.setMoney(user.getMoney().subtract(loanOrder.getBorrowMoney()));
            user.setIsPay(1);
            userService.updateById(user);
            //优惠券使用掉
            if (loanOrder.getUserCouponId() != null) {
                UserCoupon userCoupon = userCouponService.selectById(loanOrder.getUserCouponId());
                userCoupon.setStatus(2);
                userCouponService.updateById(userCoupon);
                Integer a = user.getCouponUseCount();
                user.setCouponUseCount(user.getCouponUseCount() + 1);
                userService.updateById(user);
            }
            //修改状态时间等
            loanOrder.setGmtDatetime(new Date());
            Date limitPayTime = DateUtils.dayAdd(loanOrder.getLimitDays(), new Date());
            Date overdueTime = DateUtils.dayAdd(loanOrder.getLimitDays() + loanOrder.getAllowDays(), new Date());
            loanOrder.setLimitPayTime(limitPayTime);
            loanOrder.setOverdueTime(overdueTime);
            loanOrder.setOrderStatus(1);


            //执行同盾贷前审核

            String appName = "byxd_web";//应用名称

            String biz_code = "bszcwebdq";

            EntityWrapper ew = new EntityWrapper();
            ew.eq("user_id", user.getId());
            LoanOrder lo = loanOrderService.selectOne(ew);

           /* if ("boniubao_and".equals(appName)){
                biz_code = "boniubaoand";
            }else if ("boniubao_ios".equals(appName)){
                biz_code = "boniubaoios";
            }*/
            Map<String, String> paramsMap = new HashMap<String, String>();
//            paramsMap.put("biz_code",biz_code);
//            paramsMap.put("token_id",user.getToken());
            paramsMap.put("loan_amount", lo.getNeedPayMoney().toString());
            paramsMap.put("account_mobile", user.getPhone());
            paramsMap.put("loan_term", String.valueOf(lo.getLimitDays()));
    /*        UserBank ub = userBankService.selectOne(ew);
            paramsMap.put("id_number",ub.getIdcardno());
            paramsMap.put("card_number",ub.getBankcardno());
            paramsMap.put("account_mobile",ub.getBankPhone());*/
            UserIdentity userIdentity = userIdentityService.selectOne(ew);
            paramsMap.put("account_name", userIdentity.getUserName());
            paramsMap.put("id_number", userIdentity.getIdentityNum());
            UserBasicMsg ubm = userBasicMsgService.selectOne(ew);
//            paramsMap.put("work_phone",ubm.getWorkPhone());
            paramsMap.put("contact1_mobile", ubm.getLinkPersonPhoneOne());
//            paramsMap.put("diploma",ubm.getStudy());
//            paramsMap.put("organization_address",ubm.getWorkPlace());
            paramsMap.put("contact2_name", ubm.getLinkPersonNameTwo());
//            paramsMap.put("marriage",ubm.getMarry());
            paramsMap.put("home_address", ubm.getProvince() + ubm.getCity() + ubm.getCounty() + ubm.getAddressDetails());
            paramsMap.put("contact2_mobile", ubm.getLinkPersonPhoneTwo());
//            paramsMap.put("company_name",ubm.getWorkCompany());
//            paramsMap.put("company_address",ubm.getWorkPlace());
            paramsMap.put("contact1_name", ubm.getLinkPersonNameOne());
            paramsMap.put("contact1_mobile", ubm.getLinkPersonPhoneOne());
            String cr1 = null;
            if ("父母".equals(ubm.getLinkPersonRelationOne())) {
                cr1 = "father";
            } else if ("母亲".equals(ubm.getLinkPersonRelationOne())) {
                cr1 = "mother";
            } else if ("配偶".equals(ubm.getLinkPersonRelationOne())) {
                cr1 = "spouse";
            } else if ("子女".equals(ubm.getLinkPersonRelationOne())) {
                cr1 = "child";
            } else if ("其他亲属".equals(ubm.getLinkPersonRelationOne())) {
                cr1 = "other_relative";
            } else if ("朋友".equals(ubm.getLinkPersonRelationOne())) {
                cr1 = "friend";
            } else if ("同事".equals(ubm.getLinkPersonRelationOne())) {
                cr1 = "coworker";
            } else if ("其他".equals(ubm.getLinkPersonRelationOne())) {
                cr1 = "others";
            }
            paramsMap.put("contact1_relation", cr1);
            String cr2 = null;
            if ("父母".equals(ubm.getLinkPersonRelationTwo())) {
                cr2 = "father";
            } else if ("母亲".equals(ubm.getLinkPersonRelationTwo())) {
                cr2 = "mother";
            } else if ("配偶".equals(ubm.getLinkPersonRelationTwo())) {
                cr2 = "spouse";
            } else if ("子女".equals(ubm.getLinkPersonRelationTwo())) {
                cr2 = "child";
            } else if ("其他亲属".equals(ubm.getLinkPersonRelationTwo())) {
                cr2 = "other_relative";
            } else if ("朋友".equals(ubm.getLinkPersonRelationTwo())) {
                cr2 = "friend";
            } else if ("同事".equals(ubm.getLinkPersonRelationTwo())) {
                cr2 = "coworker";
            } else if ("其他".equals(ubm.getLinkPersonRelationTwo())) {
                cr2 = "others";
            }
            paramsMap.put("contact2_relation", cr2);
            JSONObject resultJO = TongDunSDKAuth.TongDunXDBB(HttpClientUtil.buildParams(paramsMap), appName);
//            TongdunAudit tongdunAudit1 = new TongdunAudit();
//            tongdunAudit1.setRiskItems(resultJO.toString());
//            tongdunAuditService.insert(tongdunAudit1);
//            System.out.print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
//            System.out.print(resultJO.toString());
            if (resultJO.getString("reason_code") != null) {

            } else {
                TongdunAudit tongdunAudit = new TongdunAudit();
                tongdunAudit.setSuccess(resultJO.getString("success"));
                tongdunAudit.setUserId(user.getId());
                tongdunAudit.setReportId(resultJO.getString("id"));
//                tongdunAudit.setFinalScore(resultJO.getString("final_score"));
//                tongdunAudit.setFinalDecision(resultJO.getString("final_decision"));
//                tongdunAudit.setDeviceType(resultJO.getString("device_type"));
//                tongdunAudit.setApplyTime(resultJO.getString("apply_time"));
//                tongdunAudit.setReportTime(resultJO.getString("report_time"));
//                tongdunAudit.setRiskItems(resultJO.toString());
//                tongdunAudit.setAddressDetect(resultJO.getString("address_detect"));
//                tongdunAudit.setApplicationId(resultJO.getString("application_id"));
//                tongdunAudit.setCreditScore(resultJO.getString("credit_score"));
                JSONObject descJO = resultJO.getJSONObject("result_desc").getJSONObject("ANTIFRAUD");
                tongdunAudit.setFinalDecision(descJO.getString("final_decision"));
                tongdunAudit.setFinalScore(descJO.getString("final_score"));
                tongdunAudit.setRiskItems(descJO.getString("risk_items"));
                tongdunAuditService.insert(tongdunAudit);
                Integer tdS = Integer.valueOf(systemConfigService.selectValueByKey("tongdun_score"));
/*                if(tongdunAudit.getFinalDecision().equals("REJECT")){
                    EntityWrapper ew1 = new EntityWrapper();
                    ew1.eq("user_id",user.getId());
                    ew1.eq("order_status",0);
                    loanOrder.setOrderStatus(9);
                    loanOrderService.update(loanOrder,ew1);

                    user.setStatus(4);
                    user.setIsPay(0);
                    EntityWrapper ew2 = new EntityWrapper();
                    ew2.eq("id",user.getId());
                    userService.update(user,ew2);
                    return JsonResp.ok(orderId);
                }*/
            }
        } else {
            JsonResp.fa("暂时无法申请");
        }
        loanOrder.setOrderStatus(1);
        loanOrderService.updateById(loanOrder);
        return JsonResp.ok(orderId);
    }

    /**
     * @param
     * @return 返回值JsonResp
     * @分页查询订单列表
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/selectAllOrderPage", method = GET)
    public JsonResp selectAllOrderPage(Page page) {
        log.debug("分页查询订单列表");
        User user = userService.findLoginUser();
        //User user =  userService.selectById(29l);
        EntityWrapper<LoanOrder> ew = new EntityWrapper<>();
        ew.eq("user_id", user.getId());
        List<Integer> list = new ArrayList<Integer>() {{
            add(0);
            add(8);
        }};
        ew.notIn("order_status", list);
        Page loanOrderList = loanOrderService.selectPage(page, ew);
        return JsonResp.ok(loanOrderList);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @借款协议
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/selectAgreement", method = GET)
    public JsonResp selectAgreement(Long id) {
        log.debug("借款协议");
        LoanOrder loanOrder = loanOrderService.selectById(id);
        return JsonResp.ok(loanOrder.getAgreementUrl());
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @借款服务协议
     */
    @SourceAuthority(SourceType.APP)
    @RequestMapping(value = "/selectAgreementTwo", method = GET)
    public JsonResp selectAgreementTwo(Long id) {
        log.debug("借款服务协议");
        LoanOrder loanOrder = loanOrderService.selectById(id);
        return JsonResp.ok(loanOrder.getAgreementTwoUrl());
    }

    /**
     * @param
     * @return 返回值JsonResp
     * @查询申请贷款列表订单数和金额总数
     */
    @RequestMapping(value = "/countPeopleMoney2", method = GET)
    public JsonResp countPeopleMoney2(String gmtDatetime, String name, String phoneNumber) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();

        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (gmtDatetime != null && !"".equals(gmtDatetime)) {
            String time[] = gmtDatetime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);
        }

        map.put("orderStatus", 1);
        double peoplecount = loanOrderService.selectPeopleSum1(map);
        double moneycount = loanOrderService.selectMoneySum1(map);
        LoanOrder loanOrder = new LoanOrder();

        loanOrder.setTotalPeople(peoplecount);
        loanOrder.setTotalMoney(moneycount);


        return JsonResp.ok(loanOrder);


    }

    /**
     * @param page,orderStatus
     * @return 返回值JsonResp
     * @查询机审拒绝列表
     */
    @RequestMapping(value = "/selectApplyLoanList2", method = GET)
    public JsonResp selectApplyLoanList2(Page page, String gmtDatetime, String name, String phoneNumber) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (gmtDatetime != null && !"".equals(gmtDatetime)) {
            String time[] = gmtDatetime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);
        }

        map.put("orderStatus", 9);
        int count = loanOrderService.selectApplyLoanListNum(map);

        List<LoanOrder> loanOrderList = loanOrderService.selectApplyLoanList(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));
    }

    /**
     * @param page,orderStatus
     * @return 返回值JsonResp
     * @查询申请贷款列表
     */
    @Autowired
    private OrderExtendService orderExtendService;

    @RequestMapping(value = "/selectApplyLoanList", method = GET)
    public JsonResp selectApplyLoanList(Page page, String gmtDatetime, String name, String phoneNumber) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (gmtDatetime != null && !"".equals(gmtDatetime)) {
            String time[] = gmtDatetime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);
        }

        map.put("orderStatus", 1);
        int count = loanOrderService.selectApplyLoanListNum(map);


        List<LoanOrder> loanOrderList = loanOrderService.selectApplyLoanList(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);

            }
        }

        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));
    }

    @RequestMapping(value = "/selectOldOrder", method = GET)
    public JsonResp selectOldOrder(Long userId) {
        Map<String, Object> map = new HashMap<>();
        EntityWrapper ew1 = new EntityWrapper();
        System.out.print(userId);
        ew1.eq("user_id", userId);
        List<LoanOrder> uLoanOrderList = loanOrderService.selectList(ew1);
        Integer a = 0;
        Integer b = 0;
        Integer c = 0;
        BigDecimal d = new BigDecimal(0);
        if (!uLoanOrderList.isEmpty()) {
            for (LoanOrder l : uLoanOrderList) {
                if (a < l.getOverdueDays()) {
                    a = l.getOverdueDays();
                }
                if (l.getPayStatus() == 2) {
                    b++;
                }
                if (l.getOrderStatus() == 6) {
                    c++;
                }
                EntityWrapper lEW = new EntityWrapper();
                lEW.eq("order_id", l.getId());
                List<OrderExtend> orderExtendsList = orderExtendService.selectList(lEW);
                if (!orderExtendsList.isEmpty()) {
                    for (OrderExtend o : orderExtendsList) {
                        d.add(o.getExtendMoney());
                    }
                }
            }
        }
        map.put("zdyuqi", a);
        map.put("yuqics", b);
        map.put("cghuankuan", c);
        map.put("xqcishu", d);

        return JsonResp.ok(map);
    }


    /**
     * @param id
     * @return 返回值JsonResp
     * @同意申请，进入待打款状态
     */
    @RequestMapping(value = "/thisAgree", method = GET)
    public JsonResp thisAgree(long id) {
        LoanOrder loanOrder = loanOrderService.selectById(id);
        loanOrder.setOrderStatus(2);
        loanOrder.setPassTime(new Date());
        boolean bo = loanOrderService.updateById(loanOrder);
        PersonRecord pr = personRecordService.selectById(1);
        if (bo) {
            pr.setOutOrderCount(pr.getOutOrderCount() + 1);
        }
        Boolean bo1 = personRecordService.updateById(pr);
        Boolean bool = false;
        if (bo && bo1) {
            bool = true;
        }
        return JsonResp.ok(bool);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @拒绝申请，进入审核失败状态
     */
    @RequestMapping(value = "/thisRefuse", method = GET)
    public JsonResp thisRefuse(Long id) {
        //  LoanOrder loanOrder=new LoanOrder();
        LoanOrder loanOrder = loanOrderService.selectById(id);
        loanOrder.setOrderStatus(7);
        loanOrderService.updateById(loanOrder);

        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, 30);//计算30天后的时间
        Date date1 = c.getTime();

        User user = userService.selectById(loanOrder.getUserId());
        user.setIsPay(0);
        user.setStatus(4);
        user.setRefuseRemoveTime(date1);
        Double money = user.getMoney().doubleValue();
        Double borrowMoney = loanOrder.getBorrowMoney().doubleValue();
        Double temp = money + borrowMoney;
        // BigDecimal temp1=temp.
        user.setMoney(new BigDecimal(temp));
        boolean boo = userService.insertOrUpdate(user);
        //如果使用使用的优惠券返还
        if (loanOrder.getUserCouponId() != null) {
            UserCoupon userCoupon = userCouponService.selectById(loanOrder.getUserCouponId());
            userCoupon.setStatus(1);
            userCouponService.updateById(userCoupon);
        }
        // LoanOrder loanOrder1=loanOrderService.selectById(id);
        //User user=userService.selectById(loanOrder.getUserId());
        //user.setIsPay(0);


        return JsonResp.ok(boo);

    }

    /**
     * @param
     * @return 返回值JsonResp
     * @查询待打款订单数和总金额
     */
    @RequestMapping(value = "/countPeopleMoney3", method = GET)
    public JsonResp countPeopleMoney3(String gmtDatetime, String name, String phoneNumber) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();

        if (ids.size() > 0) {
            map.put("ids", ids);
        }

        if (gmtDatetime != null && !"".equals(gmtDatetime)) {
            String time[] = gmtDatetime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);
        }
        map.put("orderStatus", 2);
        double peoplecount = loanOrderService.selectPeopleSum1(map);
        double moneycount = loanOrderService.selectMoneySum1(map);
        LoanOrder loanOrder = new LoanOrder();

        loanOrder.setTotalPeople(peoplecount);
        loanOrder.setTotalMoney(moneycount);


        return JsonResp.ok(loanOrder);
    }

    /**
     * @param page,orderStatus
     * @return 返回值JsonResp
     * @查询待打款列表
     */
    @RequestMapping(value = "/toPassMoney", method = GET)
    public JsonResp toPassMoney(Page page, String passTime, String name, String phoneNumber) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }

        if (passTime != null && !"".equals(passTime)) {
            String time[] = passTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);
        }
        map.put("orderStatus", 2);
        int count = loanOrderService.selectToPassMoneyListNum(map);
        List<LoanOrder> loanOrderList = loanOrderService.selectToPassMoneyList(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));
    }


    /**
     * @param
     * @return 返回值JsonResp
     * @查询所有的已经打款订单总数和总金额
     */
    @RequestMapping(value = "/countPeopleMoney4", method = GET)
    public JsonResp countPeopleMoney4(String gmtDatetime, String name, String phoneNumber, String orderStatus) {

        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();

        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (gmtDatetime != null && !"".equals(gmtDatetime)) {
            String time[] = gmtDatetime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);
        }
        List<Integer> status = new ArrayList<>();
        if (orderStatus != null && !"".equals(orderStatus)) {
            int orderStatus1 = Integer.parseInt(orderStatus);
            status.add(orderStatus1);
        } else {
            status.add(3);
            status.add(4);
            status.add(5);
            status.add(6);
            status.add(8);
        }
        map.put("status", status);
        double peoplecount = loanOrderService.selectPeopleSum2(map);
        double moneycount = loanOrderService.selectMoneySum2(map);
        LoanOrder loanOrder = new LoanOrder();

        loanOrder.setTotalPeople(peoplecount);
        loanOrder.setTotalMoney(moneycount);


        return JsonResp.ok(loanOrder);


    }


    /**
     * @param
     * @return 返回值JsonResp
     * @查询所有的逾期订单总数和总金额
     */
    @RequestMapping(value = "/countPeopleMoney6", method = GET)
    public JsonResp countPeopleMoney6(String limitPayTime, String name, String phoneNumber, String orderStatus) {

        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();

        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (limitPayTime != null && !"".equals(limitPayTime)) {
            String time[] = limitPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);
        }
        List<Integer> status = new ArrayList<>();
        if (orderStatus != null && !"".equals(orderStatus)) {
            int orderStatus1 = Integer.parseInt(orderStatus);
            status.add(orderStatus1);
        } else {

            status.add(4);
            status.add(5);

        }
        map.put("status", status);
        double peoplecount = loanOrderService.selectPeopleSum6(map);
        double moneycount = loanOrderService.selectMoneySum6(map);
        LoanOrder loanOrder = new LoanOrder();

        loanOrder.setTotalPeople(peoplecount);
        loanOrder.setTotalMoney(moneycount);


        return JsonResp.ok(loanOrder);


    }


    /**
     * @param page,orderStatus
     * @return 返回值JsonResp
     * @查询所有的已经打款信息列表
     */
    @RequestMapping(value = "/allPassMoneyList", method = GET)
    public JsonResp allPassMoneyList(Page page, String gmtDatetime, String name, String phoneNumber, String orderStatus) {

        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }

        if (gmtDatetime != null && !"".equals(gmtDatetime)) {
            String time[] = gmtDatetime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);

        }
        List<Integer> status = new ArrayList<>();
        if (orderStatus != null && !"".equals(orderStatus)) {
            int orderStatus1 = Integer.parseInt(orderStatus);
            status.add(orderStatus1);
        } else {
            status.add(3);
            status.add(4);
            status.add(5);
            status.add(6);
            status.add(8);
        }
        map.put("status", status);
        List<LoanOrder> loanOrderList = loanOrderService.selectAllPassMoneyList(map);
        int count = loanOrderService.selectAllPassMoneyListNum(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);

                Long id = loanOrder.getAuditorId();
                if (id != null && !"".equals(id)) {
                    EntityWrapper<Admin> adminEntityWrapper = new EntityWrapper<>();
                    adminEntityWrapper.eq("id", id);
                    Admin admin;
                    admin = adminService.selectOne(adminEntityWrapper);
                    loanOrder.setAdmin(admin);
                }

            }
        }


        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));
    }

    /**
     * @param
     * @return 返回值JsonResp
     * @单个打款
     */
    @RequestMapping(value = "/passMoney", method = GET)
    public JsonResp passMoney(long id) {

        LoanOrder loanOrder = loanOrderService.selectById(id);
        loanOrder.setOrderStatus(3);
        loanOrder.setGiveTime(new Date());
        boolean bo = loanOrderService.updateById(loanOrder);
        PersonRecord pr = personRecordService.selectById(1);
        BigDecimal b1 = pr.getOutMoney();
        BigDecimal b2 = loanOrder.getRealMoney();
        pr.setOutMoney(b1.add(b2));
        Boolean bo1 = personRecordService.updateById(pr);
        Boolean bool = false;
        if (bo && bo1) {
            bool = true;
        }
        if (bo) {
            mobileService.tongDunMonitor(loanOrder);
        }
        return JsonResp.ok(bool);
    }


    @Autowired
    private TbLogService tbLogService;
    @Autowired
    private TbBaseInfoService tbBaseInfoService;
    @Autowired
    private TbReceiverService tbReceiverService;

    @RequestMapping(value = "/test", method = GET)
    public void test() {
        String taskId = "TASKDS000003201711072006070680680016";
        JSONObject resultJO = TongDunSDKAuth.TongDunSDKQuery(taskId);
        if (resultJO != null) {
            Integer code = resultJO.getInteger("code");
            if (code == 0) {
                JSONObject dataJO = resultJO.getJSONObject("data");
                if (dataJO != null) {
                    JSONObject taskDataJO = dataJO.getJSONObject("task_data");
                    if (taskDataJO != null) {
                        TbLog tbLog = new TbLog();
                        JSONObject baseInfoJO = taskDataJO.getJSONObject("base_info");
                        if (baseInfoJO != null) {
                            EntityWrapper ew = new EntityWrapper();
                            ew.eq("task_id", taskId);
                            tbLog = tbLogService.selectOne(ew);
                            TbBaseInfo tbBaseInfo = new TbBaseInfo();
                            tbBaseInfo.setUserName(baseInfoJO.getString("user_name"));
                            tbBaseInfo.setEmail(baseInfoJO.getString("email"));
                            tbBaseInfo.setUserLevel(baseInfoJO.getString("user_level"));
                            tbBaseInfo.setNickName(baseInfoJO.getString("nick_name"));
                            tbBaseInfo.setName(baseInfoJO.getString("name"));
                            tbBaseInfo.setGender(baseInfoJO.getString("gender"));
                            tbBaseInfo.setMobile(baseInfoJO.getString("mobile"));
                            tbBaseInfo.setRealName(baseInfoJO.getString("real_name"));
                            tbBaseInfo.setIdentityCode(baseInfoJO.getString("identity_code"));
                            tbBaseInfo.setVipCount(baseInfoJO.getString("vip_count"));
                            tbBaseInfo.setUserId(tbLog.getUserId());
                            tbBaseInfoService.insert(tbBaseInfo);
                        }
                        String receiver = taskDataJO.getString("receiver_list");
                        if (receiver != null) {
                            List<JSONObject> list = JSON.parseArray(receiver, JSONObject.class);
                            if (list.size() > 0) {
                                for (JSONObject j : list) {
                                    TbReceiver tbReceiver = new TbReceiver();
                                    tbReceiver.setUserId(tbLog.getUserId());
                                    tbReceiver.setName(j.getString("name"));
                                    tbReceiver.setArea(j.getString("area"));
                                    tbReceiver.setAddress(j.getString("address"));
                                    tbReceiver.setDefaultArea(j.getString("default"));
                                    tbReceiver.setMobile(j.getString("mobile"));
                                    tbReceiver.setTelephone(j.getString("telephone"));
                                    tbReceiver.setZipCode(j.getString("zip_count"));
                                    tbReceiverService.insert(tbReceiver);
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * @param
     * @return 返回值JsonResp
     * @一键全部打款
     */
    @RequestMapping(value = "/passAllMoney", method = GET)
    public JsonResp passAllMoney() {
        EntityWrapper<LoanOrder> loanOrderEntityWrapper = new EntityWrapper<>();
        loanOrderEntityWrapper.eq("order_status", 2);
        boolean bool = false;
        List<LoanOrder> loanOrderList = loanOrderService.selectList(loanOrderEntityWrapper);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                loanOrder.setOrderStatus(3);
                loanOrder.setGiveTime(new Date());
                loanOrderService.updateById(loanOrder);
                bool = true;
                mobileService.tongDunMonitor(loanOrder);
            }
        }
        return JsonResp.ok(bool);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @查询一条详情
     */
    @RequestMapping(value = "/selectOneDetail", method = GET)
    public JsonResp selectOneDetail(String id) {


        LoanOrder loanOrder = loanOrderService.selectById(id);
        User user = userService.selectById(loanOrder.getUserId());
        EntityWrapper<UserIdentity> ew = new EntityWrapper<>();
        ew.eq("user_id", user.getId());
        UserIdentity userIdentity = userIdentityService.selectOne(ew);
        user.setIdentityNum(userIdentity.getIdentityNum());
        loanOrder.setUser(user);
        Admin admin = adminService.selectById(loanOrder.getAuditorId());
        loanOrder.setAdmin(admin);
        return JsonResp.ok(loanOrder);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @拉黑用户
     */
    @RequestMapping(value = "/stopUse", method = GET)
    public JsonResp stopUse(Long id) {
        User user = userService.selectById(id);
        if (user.getStatus().equals(3)) {
            return JsonResp.fa("该用户已被禁用！");
        } else {
            user.setId(id);
            user.setStatus(3);
            Boolean boo = userService.updateById(user);

            return JsonResp.ok(boo);
        }
    }

    @RequestMapping(value = "/dropBadDebt", method = GET)
    public JsonResp dropBadDebt(Long id) {
        LoanOrder loanOrder = loanOrderService.selectById(id);
        loanOrder.setOrderStatus(8);
        Boolean bool = loanOrderService.updateById(loanOrder);
        PersonRecord personRecord = new PersonRecord();

        if (bool == true) {
            personRecord.setBadOrderCount(personRecord.getBadOrderCount() + 1);
            personRecordService.updateById(personRecord);
        }
        return JsonResp.ok(bool);

    }

    /**
     * @param
     * @return 返回值JsonResp
     * @查询打款失败订单
     */
    @RequestMapping(value = "/findPassFailPage", method = GET)
    public JsonResp findPassFailPage(Page page) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());

        int count = loanOrderService.selectFailToPassMoneyListNum(map);
        List<LoanOrder> loanOrderList = loanOrderService.selectFailToPassMoneyList(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));
    }

    /**
     * 打款失败后拒绝打款
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/refusePassMoney", method = GET)
    public JsonResp refusePassMoney(Long id) {
        LoanOrder loanOrder = loanOrderService.selectById(id);
        loanOrder.setGiveStatus(0);

        Boolean bool = loanOrderService.updateById(loanOrder);
        return JsonResp.ok(bool);

    }


    /**
     * @param
     * @return 返回值JsonResp
     * @查询申请失败订单数和金额
     */
    @RequestMapping(value = "/countPeopleMoney1", method = GET)
    public JsonResp countPeopleMoney1(String gmtDatetime, String name, String phoneNumber) {

        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (ids.size() > 0) {
            map.put("ids", ids);
        }


        if (gmtDatetime != null && !"".equals(gmtDatetime)) {
            String time[] = gmtDatetime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];

            map.put("time1", time1);
            map.put("time2", time2);
        }
        map.put("orderStatus", 7);
        double peoplecount = loanOrderService.selectPeopleSum1(map);
        double moneycount = loanOrderService.selectMoneySum1(map);
        LoanOrder loanOrder = new LoanOrder();

        loanOrder.setTotalPeople(peoplecount);
        loanOrder.setTotalMoney(moneycount);


        return JsonResp.ok(loanOrder);

    }


    /**
     * @param
     * @return 返回值JsonResp
     * @查询申请失败列表
     */
    @RequestMapping(value = "/selectFailApplyList", method = GET)
    public JsonResp selectFailApplyList(Page page, String gmtDatetime, String name, String phoneNumber) {

        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }


        if (gmtDatetime != null && !"".equals(gmtDatetime)) {
            String time[] = gmtDatetime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];

            map.put("time1", time1);
            map.put("time2", time2);
        }
        map.put("orderStatus", 7);
        int count = loanOrderService.selectFailApplyListNum(map);
        List<LoanOrder> loanOrderList = loanOrderService.selectFailApplyList(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));

    }

    /**
     * @param page
     * @param realPayTime
     * @param name
     * @param phoneNumber
     * @return 正常还款列表
     */
    @RequestMapping(value = "/normalRepaymentList", method = GET)
    public JsonResp normalRepaymentList(Page page, String realPayTime, String name, String phoneNumber) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (realPayTime != null && !"".equals(realPayTime)) {
            String time[] = realPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time1 = time[1];

            map.put("time1", time1);
            map.put("time2", time2);
        }
        map.put("payStatus", 1);
        int count = loanOrderService.selectNormalRepaymentListNum(map);
        List<LoanOrder> loanOrderList = loanOrderService.selectNormalRepaymentList(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));

    }


    /**
     * 计算正常还款的总人数和总金额
     *
     * @param realPayTime
     * @param name
     * @param phoneNumber
     * @param
     * @return
     */
    @RequestMapping(value = "/countPeopleMoney", method = GET)
    public JsonResp countPeopleMoney(String realPayTime, String name, String phoneNumber) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (realPayTime != null && !"".equals(realPayTime)) {
            String time[] = realPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time1 = time[1];

            map.put("time1", time1);
            map.put("time2", time2);
        }
        map.put("payStatus", 1);
        double peoplecount = loanOrderService.selectPeopleSum(map);
        double moneycount = loanOrderService.selectMoneySum(map);
        LoanOrder loanOrder = new LoanOrder();


        loanOrder.setTotalPeople(peoplecount);
        loanOrder.setTotalMoney(moneycount);


        return JsonResp.ok(loanOrder);
    }

    /**
     * 计算黑名单的总人数和总欠款金额
     *
     * @param
     * @param
     * @param phoneNumber
     * @param
     * @return
     */
    @RequestMapping(value = "/countPeopleMoney5", method = GET)
    public JsonResp countPeopleMoney5(String userName, String phoneNumber) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (userName != null && !"".equals(userName)) {
            userEntityWrapper.like("user_name", userName);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        userEntityWrapper.eq("status", 2);
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (!userList.isEmpty()) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        String peoplecount = loanOrderService.selectPeopleSum3(map);
        String moneycount = loanOrderService.selectMoneySum3(map);
        LoanOrder loanOrder = new LoanOrder();
        if (moneycount == null) {
            moneycount = "0";
        }
        if (peoplecount == null) {
            peoplecount = "0";
        }
        loanOrder.setTotalPeople(new Double(peoplecount));
        loanOrder.setTotalMoney(new Double(moneycount));


        return JsonResp.ok(loanOrder);


    }


    /**
     * @param page
     * @param limitPayTime
     * @param name
     * @param phoneNumber
     * @return 所有逾期列表
     */
    @RequestMapping(value = "/overDueList", method = GET)
    public JsonResp overDueList(Page page, String limitPayTime, String name, String phoneNumber, String orderStatus) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (limitPayTime != null && !"".equals(limitPayTime)) {
            String time[] = limitPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);

        }
        List<Integer> status = new ArrayList<>();
        if (orderStatus != null && !"".equals(orderStatus)) {
            int orderStatus1 = Integer.parseInt(orderStatus);
            status.add(orderStatus1);
        } else {
            status.add(4);
            status.add(5);
        }
        map.put("status", status);

        List<LoanOrder> loanOrderList = loanOrderService.selectOverDueList(map);
        int count = loanOrderService.selectOverDueListNum(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
                Admin admin = adminService.selectById(loanOrder.getAuditorId());
                loanOrder.setAdmin(admin);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));
    }


    /**
     * @param page
     * @param realPayTime
     * @param name
     * @param phoneNumber
     * @return查詢所有逾期結清列表
     */
    @RequestMapping(value = "/overDuePaymentList", method = GET)
    public JsonResp overDuePaymentList(Page page, String realPayTime, String name, String phoneNumber, Integer status) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        map.put("ids", ids);
        map.put("payStatus", 2);

        if (realPayTime != null && !"".equals(realPayTime)) {
            String time[] = realPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);

        }
        List<Integer> status1 = new ArrayList<>();
        if (status != null && !"".equals(status)) {
            status1.add(status);
        } else {
            status1.add(4);
            status1.add(5);
        }
        map.put("status1", status1);
        int count = loanOrderService.overDuePaymentListNum(map);
        List<LoanOrder> loanOrderList = loanOrderService.overDuePaymentList(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));

    }

    /**
     * @param
     * @return 返回值JsonResp
     * @查询所有的逾期结清订单总数和总金额
     */
    @RequestMapping(value = "/countPeopleMoney7", method = GET)
    public JsonResp countPeopleMoney7(String realPayTime, String name, String phoneNumber, Integer status) {

        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ids", ids);
        map.put("payStatus", 2);

        if (realPayTime != null && !"".equals(realPayTime)) {
            String time[] = realPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);

        }
        List<Integer> status1 = new ArrayList<>();
        if (status != null && !"".equals(status)) {
            status1.add(status);
        } else {
            status1.add(4);
            status1.add(5);
        }
        map.put("status1", status1);
        double peoplecount = loanOrderService.selectPeopleSum7(map);
        double moneycount = loanOrderService.selectMoneySum7(map);
        LoanOrder loanOrder = new LoanOrder();

        loanOrder.setTotalPeople(peoplecount);
        loanOrder.setTotalMoney(moneycount);


        return JsonResp.ok(loanOrder);


    }


    /**
     * @param id
     * @return 拉黑用戶
     */
    @RequestMapping(value = "/joinBlackList", method = GET)
    public JsonResp joinBlackList(Long id) {
        LoanOrder loanOrder = loanOrderService.selectById(id);
        User user = userService.selectById(loanOrder.getUserId());
        user.setStatus(2);
        Boolean bo = userService.updateById(user);

        PersonRecord pr = personRecordService.selectById(1);
        pr.setBlackCount(pr.getBlackCount() + 1);
        Boolean bo1 = personRecordService.updateById(pr);
        Boolean bool = false;
        if (bo && bo1) {
            bool = true;
        }
        return JsonResp.ok(bo);

    }

    /**
     * @return 查詢正常待还款
     */
    @RequestMapping(value = "/selectNormalToPayList", method = GET)
    public JsonResp selectNormalToPayList(Page page, String limitPayTime, String name, String phoneNumber, String orderStatus) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }

        if (limitPayTime != null && !"".equals(limitPayTime)) {
            String time[] = limitPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);
        }
        map.put("orderStatus", 3);
        int count = loanOrderService.selectNormalToPayListNum(map);
        List<LoanOrder> loanOrderList = loanOrderService.selectNormalToPayList(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));

    }

    /**
     * @return 查詢正常待还款经单数和金额
     */
    @RequestMapping(value = "/countPeopleMoney9", method = GET)
    public JsonResp countPeopleMoney9(String limitPayTime, String name, String phoneNumber, String orderStatus) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();

        if (ids.size() > 0) {
            map.put("ids", ids);
        }

        if (limitPayTime != null && !"".equals(limitPayTime)) {
            String time[] = limitPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);
        }
        map.put("orderStatus", 3);
        double peoplecount = loanOrderService.selectPeopleSum9(map);
        double moneycount = loanOrderService.selectMoneySum9(map);


        LoanOrder loanOrder = new LoanOrder();


        loanOrder.setTotalPeople(peoplecount);
        loanOrder.setTotalMoney(moneycount);


        return JsonResp.ok(loanOrder);


    }


    /**
     * @param id
     * @return
     * @throws ParseException 到期前一天发送提醒还款短信
     */
    @RequestMapping(value = "/sendMenssage", method = GET)
    public JsonResp sendMenssage(Long id) throws ParseException {
        LoanOrder loanOrder = new LoanOrder();
        if (id != null && !"".equals(id)) {
            loanOrder = loanOrderService.selectById(id);
        }
        //if (loanOrder.getLimitPayTime().getTime() == DateUtils.dayAdd(1, DateUtils.YYMMDDDate(new Date())).getTime()) {
        EntityWrapper<MsgModel> msgModelEntityWrapper = new EntityWrapper<>();
        msgModelEntityWrapper.eq("type", 2);
        // MsgModel msgModel = msgModelService.selectById(msgModelEntityWrapper);
        MsgModel msgModel = msgModelService.selectOne(msgModelEntityWrapper);
        User user = userService.selectById(loanOrder.getUserId());

        String content = msgModel.getContent().replaceAll("</?[^>]+>", "").replace("#userName", user.getUserName()).replace("#time", DateUtils.YYMMDDDateChinese(loanOrder.getGiveTime())).replace("#money", loanOrder.getNeedPayMoney().toString());

        SmsTempletEnum.REMINDSEND.setTypeName(content);
        smsService.smsCodeByType(user.getPhone(), 3);

        return JsonResp.ok();


    }

    /**
     * @param page
     * @param limitPayTime
     * @param name
     * @param phoneNumber
     * @param
     * @return 查询所有的逾期待催款列表
     */
    @RequestMapping(value = "/overDueToPayList", method = GET)
    public JsonResp overDueToPayList(Page page, String limitPayTime, String name, String phoneNumber, String orderStatus) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (limitPayTime != null && !"".equals(limitPayTime)) {
            String time[] = limitPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);

        }
        List<Integer> status = new ArrayList<>();
        if (orderStatus != null && !"".equals(orderStatus)) {
            int orderStatus1 = Integer.parseInt(orderStatus);
            status.add(orderStatus1);
        } else {
            status.add(4);
            status.add(5);
        }
        map.put("status", status);

        List<LoanOrder> loanOrderList = loanOrderService.selectOverDueList(map);
        int count = loanOrderService.selectOverDueListNum(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
                Admin admin = adminService.selectById(loanOrder.getAuditorId());
                loanOrder.setAdmin(admin);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));


    }


    @RequestMapping(value = "/myOverDueToPayList", method = GET)
    public JsonResp myOverDueToPayList(Page page, String limitPayTime, String name, String phoneNumber, String orderStatus) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (limitPayTime != null && !"".equals(limitPayTime)) {
            String time[] = limitPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            map.put("time1", time1);
            map.put("time2", time2);

        }
        List<Integer> status = new ArrayList<>();
        if (orderStatus != null && !"".equals(orderStatus)) {
            int orderStatus1 = Integer.parseInt(orderStatus);
            status.add(orderStatus1);
        } else {
            status.add(4);
            status.add(5);
        }
        map.put("status", status);
        Admin admin1 = userService.getThisLogin();
        map.put("pmId", admin1.getId());
        List<LoanOrder> loanOrderList = loanOrderService.selectOverDueList(map);
        int count = loanOrderService.selectOverDueListNum(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
                Admin admin = adminService.selectById(loanOrder.getAuditorId());
                loanOrder.setAdmin(admin);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));


    }

    @RequestMapping(value = "/selectAllPressMoneyMan", method = GET)
    public JsonResp selectAllPressMoneyMan() {
        EntityWrapper ew = new EntityWrapper();
        ew.eq("role_id", 4);
        List<Admin> list = adminService.selectList(ew);
        return JsonResp.ok(list);
    }

    @RequestMapping(value = "/setUpPressMoneyMan", method = GET)
    public JsonResp setUpPressMoneyMan(String orderId, String pmId) {
        EntityWrapper ew = new EntityWrapper();
        ew.eq("id", orderId);
        LoanOrder lo = loanOrderService.selectOne(ew);
        lo.setPressMoneyMan(Long.valueOf(pmId));
        loanOrderService.updateById(lo);
        return JsonResp.ok("成功！");
    }


    /**
     * @param page
     * @param limitPayTime
     * @param name
     * @param phoneNumber
     * @param
     * @return 查询所有的坏账列表
     */
    @RequestMapping(value = "/badDebtList", method = GET)
    public JsonResp badDebtList(Page page, String limitPayTime, String name, String phoneNumber) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (limitPayTime != null && !"".equals(limitPayTime)) {
            String time[] = limitPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];

            map.put("time1", time1);
            map.put("time2", time2);
        }
        map.put("orderStatus", 8);
        int count = loanOrderService.selectBadDebtListNum(map);
        List<LoanOrder> loanOrderList = loanOrderService.selectBadDebtList(map);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
            }
        }
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), loanOrderList, count));
    }


    /**
     * @param limitPayTime
     * @param
     * @return 拉出所有的坏账列表
     */
    @RequestMapping(value = "/excelbadDebtList", method = GET)
    public JsonResp excelbadDebtList(String limitPayTime, ModelMap modelMap) {
        EntityWrapper<LoanOrder> loanOrderEntityWrapper = new EntityWrapper<>();
        if (limitPayTime != null && !"".equals(limitPayTime)) {
            String time[] = limitPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];
            loanOrderEntityWrapper.between("limit_pay_time", time1, time2);
        }
        loanOrderEntityWrapper.eq("order_status", 8);
        List<LoanOrder> loanOrderList = loanOrderService.selectList(loanOrderEntityWrapper);
        if (!loanOrderList.isEmpty()) {
            for (LoanOrder loanOrder : loanOrderList) {
                EntityWrapper<User> userEntityWrapper1 = new EntityWrapper<>();
                userEntityWrapper1.eq("id", loanOrder.getUserId());
                User user1 = userService.selectOne(userEntityWrapper1);
                loanOrder.setUser(user1);
                EntityWrapper<Admin> adminEntityWrapper = new EntityWrapper<>();
                adminEntityWrapper.eq("id", loanOrder.getAuditorId());
                Admin admin = adminService.selectOne(adminEntityWrapper);
                loanOrder.setAdmin(admin);
            }
        }
        modelMap.put("list", loanOrderList);
        return JsonResp.ok(modelMap);
    }


    /**
     * 计算坏账的总人数和总金额
     *
     * @param
     * @param name
     * @param phoneNumber
     * @param
     * @return
     */
    @RequestMapping(value = "/countPeopleMoney8", method = GET)
    public JsonResp countPeopleMoney8(String limitPayTime, String name, String phoneNumber) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        if (name != null && !"".equals(name)) {
            userEntityWrapper.like("user_name", name);
        }
        if (phoneNumber != null && !"".equals(phoneNumber)) {
            userEntityWrapper.like("phone", phoneNumber);
        }
        List<User> userList = userService.selectList(userEntityWrapper);
        List<Long> ids = new ArrayList<>();
        if (userList.size() > 0) {
            for (User user : userList) {
                ids.add(user.getId());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (ids.size() > 0) {
            map.put("ids", ids);
        }
        if (limitPayTime != null && !"".equals(limitPayTime)) {
            String time[] = limitPayTime.split("~");
            String time1 = "";
            String time2 = "";
            time1 = time[0];
            time2 = time[1];

            map.put("time1", time1);
            map.put("time2", time2);
        }
        map.put("orderStatus", 8);
        double peoplecount = loanOrderService.selectPeopleSum8(map);
        double moneycount = loanOrderService.selectMoneySum8(map);


        LoanOrder loanOrder = new LoanOrder();


        loanOrder.setTotalPeople(peoplecount);
        loanOrder.setTotalMoney(moneycount);


        return JsonResp.ok(loanOrder);
    }


    /**
     * 根据电话号码查询个人所有贷款订单
     *
     * @param pageNo
     * @param pageSize
     * @param phone
     * @return
     */
    @RequestMapping(value = "/selectOrderLists", method = GET)
    public JsonResp selectOrderLists(Integer pageNo, Integer pageSize, String phone) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        userEntityWrapper.eq("phone", phone);
        User user = userService.selectOne(userEntityWrapper);

        EntityWrapper<LoanOrder> loanOrderEntityWrapper = new EntityWrapper<>();
        loanOrderEntityWrapper.eq("user_id", user.getId());

        Page page = loanOrderService.selectPage(new Page(pageNo, pageSize), loanOrderEntityWrapper);
        List<LoanOrder> loanOrders = page.getRecords();
        for (LoanOrder loanOrder : loanOrders) {
            loanOrder.setUser(user);
            EntityWrapper<Admin> adminEntityWrapper = new EntityWrapper<>();
            adminEntityWrapper.eq("id", loanOrder.getAuditorId());
            Admin admin = adminService.selectOne(adminEntityWrapper);
            loanOrder.setAdmin(admin);
        }
        return JsonResp.ok(new PageDto(pageNo, pageSize, page.getRecords(), page.getTotal()));


    }

    /**
     * 综合费用收益总额
     *
     * @return
     */
    @RequestMapping(value = "/allWateMoney", method = GET)
    public JsonResp allWateMoney() {

        BigDecimal wateMoney = loanOrderService.sumAllWateMoney();

        return JsonResp.ok(wateMoney);

    }

    @Autowired
    private CollectionRecordService collectionRecordService;

    /**
     * 查看当前登录用户催收记录
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/selectJiLu", method = GET)
    public JsonResp selectJiLu(String id) {
        Admin admin = userService.getThisLogin();

        EntityWrapper ew = new EntityWrapper();
        ew.eq("admin_id", admin.getId());
        ew.eq("order_id", id);

        List<CollectionRecord> cList = collectionRecordService.selectList(ew);

        return JsonResp.ok(cList);
    }

    @RequestMapping(value = "/jilubaocun", method = GET)
    public JsonResp jilubaocun(String orderId, String text) {
        Admin admin = userService.getThisLogin();
        EntityWrapper ew = new EntityWrapper();
        ew.eq("order_id", orderId);
        List<CollectionRecord> crl = collectionRecordService.selectList(ew);
        for (CollectionRecord c : crl) {
            c.setAdminId(admin.getId());
            collectionRecordService.update(c, ew);
        }
        CollectionRecord cr = new CollectionRecord();
        cr.setText(text);
        cr.setAdminId(admin.getId());
        cr.setOrderId(Long.valueOf(orderId));
        collectionRecordService.insert(cr);
        return JsonResp.ok("success");
    }

    /**
     * 查询我的催收记录
     *
     * @return
     */
    @RequestMapping(value = "/allMyLoanList", method = GET)
    public JsonResp allMyLoanList() {
        Admin admin = userService.getThisLogin();
        Map<Object, Object> map = new HashMap<>();
        List<CollectionRecord> crl = collectionRecordService.selectAdminLoan(admin.getId());
        List<LoanOrder> list = new ArrayList<>();
        for (CollectionRecord c : crl) {
            EntityWrapper ew = new EntityWrapper();
            ew.eq("order_id", c.getOrderId());
            LoanOrder l = loanOrderService.selectOne(ew);
            list.add(l);
        }
        map.put("list", list);
        java.math.BigDecimal sun = null;
        for (LoanOrder lo : list) {
            if (lo.getOrderStatus() == 6) {
                sun.add(lo.getNeedPayMoney());
            }
        }
        map.put("tichen", sun.doubleValue());
        return JsonResp.ok(map);
    }


    /**
     * @param orderId
     * @param money
     * @return
     */
    @RequestMapping(value = "/bufenhuankuan", method = GET)
    public JsonResp bufenhuankuan(String orderId, String money) {
        try {
            java.math.BigDecimal cMoney = new BigDecimal(money);
            cMoney = cMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
            EntityWrapper ew = new EntityWrapper();
            ew.eq("id", orderId);
            LoanOrder ld = loanOrderService.selectOne(ew);
            java.math.BigDecimal oldMoney = ld.getConsultRepaymentMoney();
            cMoney = oldMoney.add(cMoney);
            ld.setConsultRepaymentMoney(cMoney);
            loanOrderService.updateById(ld);
            return JsonResp.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResp.fa("操作失败。");
        }

    }

    /**
     * @param orderId
     * @param money
     * @return
     */
    @RequestMapping(value = "/jieqinhuankuan", method = GET)
    public JsonResp jieqinhuankuan(String orderId, String money) {
        try {
            java.math.BigDecimal cMoney = new BigDecimal(money);
            cMoney = cMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
            EntityWrapper ew = new EntityWrapper();
            ew.eq("id", orderId);
            LoanOrder ld = loanOrderService.selectOne(ew);
            java.math.BigDecimal oldMoney = ld.getConsultRepaymentMoney();
            cMoney = oldMoney.add(cMoney);
            ld.setConsultRepaymentMoney(cMoney);
            ld.setOrderStatus(6);
            ld.getPayStatus();
            loanOrderService.updateById(ld);
            EntityWrapper ew2 = new EntityWrapper();
            ew2.eq("id", ld.getUserId());
            User user = userService.selectOne(ew2);
            user.setStatus(2);
            userService.updateById(user);
            return JsonResp.ok();
        } catch (Exception e) {
            return JsonResp.fa("操作失败。");
        }

    }

    @Autowired
    private SysAreaService sysAreaService;
    @Autowired
    private RefuseAreaService refuseAreaService;

    @RequestMapping(value = "/selectRefuseArea", method = GET)
    public JsonResp selectRefuseArea(Page page) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        Map cMap = new HashMap();
        List<SysArea> list = refuseAreaService.selectByMap(cMap);
        return JsonResp.ok(new PageDto(page.getCurrent(), page.getSize(), list, list.size()));
    }

    @RequestMapping(value = "/addRefuseArea", method = GET)
    public JsonResp addRefuseArea(String areaName) {
        List<SysArea> list = sysAreaService.selectLikeName("%" + areaName + "%");
        for (SysArea s : list) {
            EntityWrapper ew = new EntityWrapper();
            ew.eq("area_code", s.getAreaCode());
            Integer a = refuseAreaService.selectCount(ew);
            if (a == 0) {
                RefuseArea refuseArea = new RefuseArea();
                refuseArea.setAreaCode(s.getAreaCode());
                refuseArea.setAreaName(s.getAreaName());
                refuseAreaService.insert(refuseArea);
            }
        }
        return JsonResp.ok("success");
    }

    @RequestMapping(value = "/deleteRefuseArea", method = GET)
    public JsonResp deleteRefuseArea(String id) {
        EntityWrapper ew = new EntityWrapper();
        ew.eq("id", id);
        refuseAreaService.delete(ew);
        return JsonResp.ok("success");
    }

    /**
     * 后台确认还款
     *
     * @return
     */
    @RequestMapping(value = "/receiveMoneyAdmin", method = RequestMethod.GET)
    public JsonResp receiveMoneyAdmin(Long orderId) {
        log.debug("后台确认还款");
        LoanOrder loanOrder = loanOrderService.selectById(orderId);
        User user = userService.selectById(loanOrder.getUserId());
        if (loanOrder != null && loanOrder.getOrderStatus() != 6) {
            loanOrder.setOrderStatus(6);
            try {
                if (DateUtils.YYMMDDDate(new Date()).getTime() > loanOrder.getOverdueTime().getTime()) {
                    loanOrder.setPayStatus(2);//超出容限期还款
                    user.setMoney(user.getMoney().add(loanOrder.getBorrowMoney()));
                } else {
                    loanOrder.setPayStatus(1);//正常还款
                    user.setMoney(user.getMoney().add(loanOrder.getBorrowMoney()));
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            loanOrder.setRealPayMoney(loanOrder.getNeedPayMoney());
            loanOrder.setRealPayTime(new Date());
            loanOrderService.updateById(loanOrder);

            user.setIsPay(0);
            user.setIsOld(1);
            userService.updateById(user);

        }
        return JsonResp.ok(loanOrder);
    }
}